Creating a Map in Python for Plotting

Import Libraries

  • Folium allows you to create interactive leaflet maps
  • Pandas allows for reading CSV files and turning it into a DataFrame
import folium
import pandas as pd
from folium.plugins import HeatMap

Read the CSV file

data = pd.read_excel("United_States_Offense_Type_by_Agency_2022.xlsx", sheet_name='Sheet2')
# data

Create a map centered around the US

import ipywidgets as widgets
from IPython.display import display

# Define options for the dropdown
options = ["Total\nOffenses", "Crimes\nAgainst\nPersons", "Crimes\nAgainst\nProperty", "Crimes\nAgainst\nSociety"]


# Create the dropdown widget
dropdown = widgets.Dropdown(options=options, description='Select an option:')

# Define a function to handle the selection
def on_change(change):
    if change['type'] == 'change' and change['name'] == 'value':
        print("Selected:", change['new'])

# Attach the function to the dropdown's event handler
dropdown.observe(on_change)

# Display the dropdown widget
display(dropdown)
Selected: Crimes
Against
Property
map_us = folium.Map(location=[37.0902, -95.7129], zoom_start=4) 
for index, row in data.iterrows():
    #Location
    location = row['Location']
    #Latitude
    lat = row['Latitude']
    # if latitude is NaN
    if pd.isna(lat): 
        continue
    #Longitude
    lon = row['Longitude']
    
    # Value being displayed based on dropdown selection
    value = row[dropdown.value]
    folium.CircleMarker(location=[lat, lon], 
                        radius=value/5000, color='rgb(178,34,34)', 
                        fill=True, fill_color='rgb(178,34,34)', 
                        fill_opacity=0.3, 
                        weight=1,
                        tooltip=f"Location: {location} \n Value: {value}").add_to(map_us)
map_us
Make this Notebook Trusted to load map: File -> Trust Notebook

Add Markers

add markers at specific locations on the map. You can specify the latitude and longitude coordinates for each marker.

map_us.save("us_map.html")